require("../common/lodash-fix");
import omit from "lodash.omit";
import get from "lodash.get";

// loading配置，请求次数统计
function startLoading() {
  wx.showLoading({
    title: "加载中...",
    mask: true,
  });
}
function endLoading() {
  wx.hideLoading();
}

// 声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}

export const request = (config) => {
  showFullScreenLoading();
  let requestTask;
  const app = getApp();
  const BASE_URL = app.globalData.BASE_URL;
  try {
    const url =
      config?.url?.startsWith("https") || config?.url?.startsWith("http")
        ? config?.url
        : `${BASE_URL}${config?.url}`;
    return new Promise((resolve) => {
      const memberId = wx.getStorageSync("userInfo")?.id
      requestTask = wx.request({
        url,
        header: { ...get(config, ["header"], {}) },
        data: memberId ? {
          ...config?.data,
          memberId
        } : config.data,
        ...omit(config, "header", "url", "skipToken", "data"),
        success: async (res) => {
          console.log({ code: res?.data });
          tryHideFullScreenLoading();
          if (res?.statusCode === 200) {
            if (res?.data?.code?.toString() === "0") {
              // requestTask.abort() 可以取消请求
              resolve([res?.data, requestTask]);
            } else if (res?.data?.code?.toString() === "10001") {
              wx.reLaunch({
                url: "/pages/login/login",
              });
              wx.clearStorageSync();
            } else {
              wx.showToast({
                icon: "none",
                title: res?.data?.msg || "请求失败，请重试",
              });
            }
          } else {
            console.log({ res });
            if (res.statusCode === 401 || res.statusCode === 424 || res.statusCode === 403) {
              wx.reLaunch({
                url: "/pages/login/login",
              });
              wx.clearStorageSync();
            }
            wx.showToast({
              icon: "none",
              title: res?.data?.msg || "请求失败，请重试",
            });
          }
        },
        fail: (err) => {
          tryHideFullScreenLoading();
          wx.showToast({
            icon: "none",
            title: err?.errMsg || "请求失败，请重试",
          });
        },
        complete: () => {
          // console.log({ complete: url })
          tryHideFullScreenLoading();
          resolve([{ code: "error", msg: "" }, requestTask]);
        },
      });
    });
  } catch (e) {
    console.log("error: ", e);
    tryHideFullScreenLoading();
    return [{ code: "error", msg: "请求失败" }, requestTask];
  }
};
